import datetime
import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from commond.read_config import ReadConfig


class Sendmail(object):

    def __init__(self, config_name, project_name):
        """
        读取的配置文件名称及其所对应的项目名称
        :param config_name
        :param project_name
        """
        self.project_name = project_name
        self.readconfig = ReadConfig(config_name, project_name)
        self.mail_host = self.readconfig.get_email("EMAIL", "mail_host")
        self.mail_user = self.readconfig.get_email("EMAIL", "mail_user")
        self.mail_pass = self.readconfig.get_email("EMAIL", "mail_pass")
        self.sender = self.readconfig.get_email("EMAIL", "sender")
        self.receivers = self.readconfig.get_email("EMAIL", "receivers")
        self.cc_mail = self.readconfig.get_email("EMAIL", "cc_mail")
        self.sender_name = self.readconfig.get_email("EMAIL", "sender_name")

    def send_email(self, report):
        message = MIMEMultipart()  # 创建一个带附件的实例
        # message = MIMEText(open(mail_path, 'rb').read().decode(), "html") #  直接发送html格式报告
        message['From'] = formataddr([self.sender_name, self.sender])
        message['To'] = self.receivers
        message['Cc'] = self.cc_mail
        subject = self.readconfig.get_email("EMAIL", "subject") + str(datetime.datetime.now())[5:19]
        message['Subject'] = Header(subject, 'utf-8')
        message["Accept-Language"] = "zh-CN"
        message["Accept-Charset"] = "ISO-8859-1,utf-8,gbk"
        # att = MIMEBase('application', 'octet-stream')

        att = MIMEApplication(open(report, 'rb').read())
        att.add_header('Content-Disposition', 'attachment',
                       filename=('gbk', '', self.project_name + '_Test_Report.html'))
        message.attach(MIMEText(self.readconfig.get_email("EMAIL", "mail_txt"), 'plain', 'utf-8'))
        message.attach(att)  # 发送附件

        try:
            smtpObj = smtplib.SMTP(self.mail_host)
            smtpObj.login(self.mail_user, self.mail_pass)
            smtpObj.sendmail(self.sender, self.receivers.split(",") + self.cc_mail.split(","), message.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException as e:
            print("Error: 无法发送邮件", e)


if __name__ == "__main__":
    pass
